/**
 * @Description: 消息列表
 * @author 阮荣强
 * @date 2019/12/23
 */
import {Button, Card, Checkbox, Form, Icon, Input, Table, Typography} from 'antd';
import React, {Component, Fragment} from 'react';
import {formatMessage} from 'umi/locale';
import {requestPromise} from '@/utils/request';
import {getWebPath} from '../../../utils/request';
import uiUtils from '../../../utils/uiUtils';

const {Text} = Typography;
const {Search} = Input;
const FormItem = Form.Item;

//伪造数据
const fakeDataNoticeData = [];
for (let i = 0; i < 100; i++) {
  const obj = {
    datetime: "2019-08-22 17:48:31",
    read: i % 2 === 0,
    description: "<p>测试内容内容<br/><h5>h5</h5></p>",
    avatar: "https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png",
    id: i + 100,
    title: `测试消息${i}`,
    type: "notification",
  };
  fakeDataNoticeData.push(obj);
}

@Form.create()
class WebMessage extends Component {

  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      noticeData: [],
    };
    this.getMessage();
  }

  getMessage = (titleOrContent, read) => {
    requestPromise(`${getWebPath()}sys/user/msg/getMessages?titleOrContent=${titleOrContent || ''}&read=${read || ''}`, {
      method: 'GET',
    }).then(res => {
      if (res && res.code === 0) {
        this.setState({
          noticeData: res.data.list,
        });
      }
    });
  };

  //仅看未读
  checkBoxOnChange = e => {
    this.getMessage(undefined, e.target.checked);
  };

  //批量消息已读
  updateReadStatus = () => {
    const selectedRows = this.state.selectedRows || [];
    const ids = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      ids.push(selectedRows[i].id);
    }
    if (ids.length !== 0) {
      this.setState({
        loading: true,
      });
      requestPromise(`${getWebPath()}sys/user/msg/updateReadStatus`, {
        method: 'POST',
        body: ids,
      }).then(res => {
        this.setState({
          loading: false,
        });
        if (res && res.code === 0) {
          uiUtils.showMessage(
            formatMessage({id: 'ours.curd.show-alert.operate-success'}),
            'success'
          );
          this.getMessage();
        }
      });
    }
  };

  //删除消息
  delMessage = () => {
    const selectedRows = this.state.selectedRows || [];
    const ids = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      ids.push(selectedRows[i].id);
    }
    if (ids.length !== 0) {
      this.setState({
        loading: true,
      });
      requestPromise(`${getWebPath()}sys/user/msg/delete`, {
        method: 'POST',
        body: ids,
      }).then(res => {
        this.setState({
          loading: false,
        });
        if (res && res.code === 0) {
          uiUtils.showMessage(
            formatMessage({id: 'ours.curd.show-alert.operate-success'}),
            'success'
          );
          this.getMessage();
        }
      });
    }
  };

  //消息展开月度处理
  onExpand = (expanded, record) => {
    console.log(expanded);
    console.log(record);
    //true 表示展开
    if (expanded && record.read === false) {
      const noticeData = this.state.noticeData || [];
      //更改为已读
      noticeData.forEach(value => {
        if (value.id === record.id) {
          value.read = true;
        }
      });

      const ids = [record.id];
      if (ids.length !== 0) {
        requestPromise(`${getWebPath()}sys/user/msg/updateReadStatus`, {
          method: 'POST',
          body: ids,
        }).then(res => {
          console.log(res);
        });
      }
    }
  };

  render() {
    const style = {
      style: {
        marginLeft: 10,
        marginTop: 10,
      },
    };

    const ItemLayout = {
      labelCol: {span: 3},
      wrapperCol: {span: 20}, //5+19=24,少一个栅格
    };
    const formItemLayout = {
      labelCol: {span: 3},
      wrapperCol: {span: 21}, //5+19=24,少一个栅格
    };
    const colSpanLayout = {md: 24, sm: 24}; //每一col跨?列
    const rowGutterPxLayout = {md: 24, sm: 24}; //col之间的间隔?px
    const {
      form: {getFieldDecorator},
    } = this.props;

    const expandedRowRender = record => <div dangerouslySetInnerHTML={{__html: record.description}}/>;

    const columns = [
      {
        title: '标题',
        dataIndex: 'title',
        key: 'title',
        width: 350,
        render: (text, record) => {
          if (record.read) {
            return <Text type="secondary">{text}</Text>;
          }
          return <a>{text}</a>;
        },
      },
      {
        title: '接收时间',
        dataIndex: 'datetime',
        key: 'datetime',
        width: 180
      },
      {
        title: '',
        key: 'action',
        render: (text, record) => (
          <span style={{float: "right"}}>
            <a className="ant-dropdown-link">
              <Icon type="down"/>
            </a>
          </span>
        ),
      },
    ];

    const rowSelection = {
      hideDefaultSelections: true /*去掉全选和反选*/,
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({
          selectedRows,
        });
      },
    };

    console.log(this.state);

    return (
      <Fragment>
        <div style={{marginBottom: 5}}>
          <Checkbox onChange={this.checkBoxOnChange}>仅看未读消息</Checkbox>
        </div>
        <Card
          loading={this.state.loading}
          bordered
          size="small"
          extra={
            <Search
              placeholder="input search text"
              onSearch={value => this.getMessage(value, undefined)}
              style={{width: 200}}
            />}
          title={<Fragment>
            <Button size="small" onClick={this.updateReadStatus}>标记为已读</Button>
            <Button style={{marginLeft: 10}} size="small" type="danger" onClick={this.delMessage}>删除</Button>
          </Fragment>}
        >
          <Table
            expandedRowRender={expandedRowRender}
            expandRowByClick
            dataSource={this.state.noticeData}
            columns={columns}
            rowSelection={rowSelection}
            onExpand={this.onExpand}
          />
        </Card>
      </Fragment>
    );
  }
}

export default WebMessage;
